# https://github.com/quanttide/fastapi-tenants/issues/2
from fastapi import FastAPI, Depends, HTTPException, Request
from pydantic import BaseModel

app = FastAPI()

class TenantContext:
    def __init__(self, tenant_id):
        self.tenant_id = tenant_id

class Tenant(BaseModel):
    id: str

@app.middleware("http")
async def add_tenant_context(request: Request):
     tenant_id = request.headers.get("X-Tenant-ID") # 从请求标头获取租户标识
     request.state.tenant = TenantContext(tenant_id)

@app.get("/resource")
async def get_resource(tenant: Tenant = Depends(get_tenant)):
     return {"message": f"Resource for Tenant {tenant.id}"}

def get_tenant(request: Request = Depends()):
    if request.state.tenant:
        return request.state.tenant
    else:
        raise HTTPException(status_code=401, detail="Tenant not specified")